package com.woniuxy.controller;

import com.woniuxy.domain.Dept;
import com.woniuxy.domain.ResultVO;
import com.woniuxy.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author gaopeng
 * @create 2020/03/2020/3/25 11:38:49
 */
@RestController
@RequestMapping("depts")
public class DeptController {

    @Autowired
    private IDeptService service;

    @GetMapping
    @ResponseBody
    public ResultVO findAll() {
        List<Dept> list = service.findAll();

        ResultVO resultVO = null;
        if(list != null && list.size() > 0) {
            resultVO = new ResultVO(200,"查询所有部门成功", list);
        } else {
            resultVO = new ResultVO(500, "查询所有部门失败");
        }
        return resultVO;
    }

    // 适配器处理器，会先检查方法的参数是否有@RequestBody
    // 如果没有@RequestBody，就把请求参数按照键值对的方式注入给参数。
    // 如果有@RequestBody，就会检查请求头中的Content-Type的取值，找对应的HttpMessageConverter
    // Content-Type: application/json, StringHttpMessagerConverter  JackSon2MappingHttpMessageConverter
    // supports:                          Stirng.class == Dept.class        直接返回true
    // 最终就使用JackSon2MappingHttpMessageConverter来把请求参数放入目标参数中，按照json的规则来解析，并存放。
    @PostMapping("save")
    public ResultVO save(@RequestBody Dept dept) {
        try {
            service.save(dept);
            return new ResultVO(200, "增加数据成功", dept);
        } catch (Exception e) {
            return new ResultVO(500, "增加数据失败", dept);
        }
    }

    @GetMapping("{did}")
    public ResultVO findOne(@PathVariable Integer did) {
        Dept dept = service.findOne(did);
        if(dept != null) {
            return new ResultVO(200, "查询dept成功", dept);
        } else {
            return new ResultVO(500, "查询dept失败");
        }
    }

    @DeleteMapping("{did}")
    public ResultVO delete(@PathVariable Integer did) {
        try {
            service.delete(did);
            return new ResultVO(200, "删除数据成功", did);
        } catch (Exception e) {
            return new ResultVO(500, "删除数据失败", did);
        }
    }

    @PutMapping
    public ResultVO update(@RequestBody Dept dept) {
        try {
            service.update(dept);
            return new ResultVO(200, "修改数据成功", dept);
        } catch (Exception e) {
            return new ResultVO(500, "修改数据失败", dept);
        }
    }

}
